package com.histone.lilian.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.template.Template;
import cn.hutool.extra.template.TemplateConfig;
import cn.hutool.extra.template.TemplateEngine;
import cn.hutool.extra.template.TemplateUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.ssssssss.magicapi.core.config.JsonCodeConstants;
import org.ssssssss.magicapi.core.model.ApiInfo;
import org.ssssssss.magicapi.core.model.Group;
import org.ssssssss.magicapi.core.service.MagicResourceService;

import java.util.Map;

import static org.ssssssss.magicapi.core.config.Constants.ROOT_ID;

/**
 * 代码生成
 * @author histone
 */
@Service
public class GenService implements JsonCodeConstants {

    private final static String API_OPTION = "[{\"name\":\"permission\",\"value\":\"free:{}:{}\",\"description\":\"允许拥有该权限的访问\"}]";
    private TemplateEngine engine = TemplateUtil.createEngine(new TemplateConfig("templates", TemplateConfig.ResourceMode.CLASSPATH));

    private final MagicResourceService magicResourceService;

    public GenService(MagicResourceService magicResourceService) {
        this.magicResourceService = magicResourceService;
    }

    /**
     * 生成 增删改查等 接口
     * @param tableName     表名
     * @param tableLabel    表显示名
     * @return
     */
    @Transactional(rollbackFor = { Exception.class })
    public String execute(String tableName, String tableLabel) {
        // 生成分组
        Group group = new Group();
        group.setName("自动生成_" + tableLabel);
        group.setParentId(ROOT_ID);
        group.setPath("freeData");
        group.setType("api");

        boolean saveGroup = magicResourceService.saveGroup(group);
        if (!saveGroup) {
            return null;
        }

        // 生成接口
        Dict params = Dict.create()
//                .set("creator", StpUtil.getLoginId())
                .set("createTime", DateUtil.now())
                .set("tableName", tableName)
                .set("tableLabel", tableLabel);
        // 增
        this.genAddApi(tableName, tableLabel, group.getId(), params);
        // 删
        this.genDelApi(tableName, tableLabel, group.getId(), params);
        // 改
        this.genEditApi(tableName, tableLabel, group.getId(), params);
        // 查
        this.genListApi(tableName, tableLabel, group.getId(), params);
        // 导出
        this.genExportApi(tableName, tableLabel, group.getId(), params);

        return group.getId();
    }

    /**
     * 列表查询
     */
    private void genListApi(String tableName, String tableLabel, String groupId, Map tempParams) {
        ApiInfo info = new ApiInfo();
        info.setMethod("GET");
        info.setName(tableLabel + "列表");
        info.setPath(tableName);
        info.setGroupId(groupId);
        info.setLock("0");
        info.setOption(StrUtil.format(API_OPTION, tableName, "list"));

        Template template = engine.getTemplate("templates/gen/apiList.vtl");
        info.setScript(template.render(tempParams));

        magicResourceService.saveFile(info);
    }

    /**
     * 详情查询
     */
    private void genDetailApi(String tableName, String tableLabel, String groupId, Map tempParams) {
        ApiInfo info = new ApiInfo();
        info.setMethod("GET");
        info.setName(tableLabel + "详情");
        info.setPath(tableName + "/{id}");
        info.setGroupId(groupId);
        info.setLock("0");
        info.setOption(StrUtil.format(API_OPTION, tableName, "query"));

        Template template = engine.getTemplate("templates/gen/apiDetail.vtl");
        info.setScript(template.render(tempParams));

        magicResourceService.saveFile(info);
    }

    /**
     * 新增
     */
    private void genAddApi(String tableName, String tableLabel, String groupId, Map tempParams) {
        ApiInfo info = new ApiInfo();
        info.setMethod("POST");
        info.setName(tableLabel + "新增");
        info.setPath(tableName);
        info.setGroupId(groupId);
        info.setLock("0");
        info.setOption(StrUtil.format(API_OPTION, tableName, "add"));

        Template template = engine.getTemplate("templates/gen/apiAdd.vtl");
        info.setScript(template.render(tempParams));

        magicResourceService.saveFile(info);
    }

    /**
     * 删除
     */
    private void genDelApi(String tableName, String tableLabel, String groupId, Map tempParams) {
        ApiInfo info = new ApiInfo();
        info.setMethod("DELETE");
        info.setName(tableLabel + "删除");
        info.setPath(tableName + "/{ids}");
        info.setGroupId(groupId);
        info.setLock("0");
        info.setOption(StrUtil.format(API_OPTION, tableName, "remove"));

        Template template = engine.getTemplate("templates/gen/apiDel.vtl");
        info.setScript(template.render(tempParams));
        magicResourceService.saveFile(info);
    }

    /**
     * 修改
     */
    private void genEditApi(String tableName, String tableLabel, String groupId, Map tempParams) {
        ApiInfo info = new ApiInfo();
        info.setMethod("PUT");
        info.setName(tableLabel + "修改");
        info.setPath(tableName);
        info.setGroupId(groupId);
        info.setLock("0");
        info.setOption(StrUtil.format(API_OPTION, tableName, "edit"));

        Template template = engine.getTemplate("templates/gen/apiEdit.vtl");
        info.setScript(template.render(tempParams));
        magicResourceService.saveFile(info);
    }

    /**
     * 导出
     */
    private void genExportApi(String tableName, String tableLabel, String groupId, Map tempParams) {
        ApiInfo info = new ApiInfo();
        info.setMethod("POST");
        info.setName(tableLabel + "导出");
        info.setPath(tableName + "/export");
        info.setGroupId(groupId);
        info.setLock("0");
        info.setOption(StrUtil.format(API_OPTION, tableName, "export"));

        Template template = engine.getTemplate("templates/gen/apiExport.vtl");
        info.setScript(template.render(tempParams));
        magicResourceService.saveFile(info);
    }

}
